package com.ts.common.core.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ts.common.core.exception.TSException;

import java.util.Date;

public class JWTUtils {

    private static Algorithm sign = Algorithm.HMAC256("ts-cloudCircle");

    /**
     * 生成一个Token，把key和value放入到JWT的载荷
     * @param key
     * @param val
     * @return
     */
    public static String getToken(String key, Object val){
        return JWT.create().withClaim(key, JSON.toJSONString(val)).sign(sign);
    }

    /**
     * 生成一个Token，把key和value放入到JWT的载荷,具备过期时
     * @param key
     * @param val
     * @param time
     * @return
     */
    public static String getToken(String key,Object val,Long time){
        Date exp = new Date(System.currentTimeMillis() + time);
        return JWT.create().withClaim(key,JSON.toJSONString(val)).withExpiresAt(exp).sign(sign);
    }

    /**
     * 校验token，token校验成功返回DecodedJWT对象
     * @param token
     * @return
     */
    public static DecodedJWT checkToken(String token) {
        try {
            return JWT.require(sign).build().verify(token);
        } catch (TokenExpiredException e) {
            throw new TSException("Token已过期");
        } catch (JWTVerificationException e) {
            throw new TSException("Token校验异常");
        }
    }


}
